package com.android.xk.mask.client

import com.android.xk.mask.event.MessageEvent
import com.android.xk.mask.model.Message
import com.apkfuns.logutils.LogUtils
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.handler.timeout.IdleState
import io.netty.handler.timeout.IdleStateEvent
import org.simple.eventbus.EventBus
import java.util.concurrent.TimeUnit

class MessageHandler : SimpleChannelInboundHandler<Message>()
{
    override fun channelRead0(ctx: ChannelHandlerContext?, msg: Message?)
    {
        LogUtils.i(msg)
        msg?.let {
            EventBus.getDefault().post(MessageEvent(it))
        }
    }

    override fun channelRead(ctx: ChannelHandlerContext?, msg: Any?)
    {
        LogUtils.e(msg)
        super.channelRead(ctx, msg)
    }

    override fun channelInactive(ctx: ChannelHandlerContext?)
    {
        LogUtils.e("与服务器断开连接")
        ctx?.let {
            val s = it.channel().eventLoop().schedule({
                SocketClient.reconnect()
            }, 2, TimeUnit.SECONDS)
            it.close()
        }
        super.channelInactive(ctx)
    }
}